/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package nominalitzacions.ui;

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;

/**
 *
 * @author genis.sole
 */

public class LanguageView extends JFrame {
    private LanguageViewController LVC;

    private JFileChooser fc = new JFileChooser();
    private JPanel centralPanel = new JPanel();
    private JPanel buttonsPanel = new JPanel();
    private JPanel mainPanel = new JPanel();
    private JTextField infPathTextField = new JTextField();
    private JTextField corpPathTextField = new JTextField();
    private JTextField nounPathTextField = new JTextField();
    private JTextField irrPathTextField = new JTextField();
    private JLabel infLabel = new JLabel("Infinitives path:");
    private JLabel corpLabel = new JLabel("Corpus path:");
    private JLabel langLabel = new JLabel("Language:");
    private JLabel nounLabel = new JLabel("Nouns path:");
    private JLabel irrLabel = new JLabel("Irr. verbs path:");
    private JButton corpButton = new JButton("Browse...");
    private JButton irrButton = new JButton("Browse...");
    private JButton nounButton = new JButton("Browse...");
    private JButton infButton = new JButton("Browse...");
    private JButton doneButton = new JButton("Done");
    private JButton okButton = new JButton("Add");
    private JButton delButton = new JButton("Delete");
    private JComboBox langComboBox = new JComboBox();

    public LanguageView(LanguageViewController LVC) {
        this.LVC = LVC;
        iniComponents();
    }

    private void iniComponents() {
        iniFrame();
        iniMainPanel();
        assignListeners();
        inilangComboBox();
    }

    private void actionPerformedPathButtons(ActionEvent event, String msg) {
        int returnVal = fc.showDialog(this, "Choose " + msg);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (event.getSource() == infButton) {
                infPathTextField.setText(file.getAbsolutePath());
            } else if (event.getSource() == corpButton) {
                corpPathTextField.setText(file.getAbsolutePath());
            } else if (event.getSource() == irrButton) {
                irrPathTextField.setText(file.getAbsolutePath());
            } else {
                nounPathTextField.setText(file.getAbsolutePath());
            }
            this.pack();
            this.repaint();
        }
    }
    
    private void setPathTextFields(String lang) {
        infPathTextField.setText(LVC.getInfPath(lang));
        corpPathTextField.setText(LVC.getCorpPath(lang));
        nounPathTextField.setText(LVC.getNounsPath(lang));
        irrPathTextField.setText(LVC.getIrrPath(lang));
    }

    private void actionPerformedLangComboBox() {
        String lang = (String) langComboBox.getSelectedItem();
        if (LVC.containsLang(lang)) {
            setPathTextFields(lang);
            okButton.setText("Save");
            delButton.setEnabled(true);
        }
        this.pack();
        this.repaint();
    }

    private void actionPerformedLangComboBoxEdit() {
        String lang = (String) langComboBox.getEditor().getItem();
        if (LVC.containsLang(lang)) {
            setPathTextFields(lang);
            okButton.setText("Save");
            delButton.setEnabled(true);
        } else {
            infPathTextField.setText("");
            corpPathTextField.setText("");
            nounPathTextField.setText("");
            irrPathTextField.setText("");
            okButton.setText("Add");
            delButton.setEnabled(false);
        }
        this.pack();
        this.repaint();
    }

    private boolean checkEmpty() {
        boolean check = true;
        String lang = (String)langComboBox.getEditor().getItem();
        if(lang == null || lang.equals("")) {
            check = false;
        }
        if(infPathTextField.getText().equals("")) {
            check = false;
        }
        if(corpPathTextField.getText().equals("")) {
            check = false;
        }
        if(nounPathTextField.getText().equals("")) {
            check = false;
        }
        if(irrPathTextField.getText().equals("")) {
            check = false;
        }
        okButton.setEnabled(check);
        return check;
    }

    private void actionPerformedOkButton(ActionEvent event) {
        String langName = (String)langComboBox.getEditor().getItem();
        langName = langName.trim();
        try {
            if (delButton.isEnabled()) {
                if (checkEmpty()) {
                    Object[] options = {"Yes", "No"};
                    int n = JOptionPane.showOptionDialog(this, 
                          "Do you want to save the changes to de language "
                          + langName + "?","Save",
                          JOptionPane.YES_NO_OPTION,
                          JOptionPane.QUESTION_MESSAGE, null, options,
                          options[1]);
                    if (n == 0) {
                        LVC.addLanguage(langName, infPathTextField.getText(),
                                irrPathTextField.getText(), nounPathTextField.getText(),
                                corpPathTextField.getText());
                    } else {
                        setPathTextFields(langName);
                    }
                } else {
                    setPathTextFields(langName);
                }
            } else {
                if (checkEmpty()) {
                    LVC.addLanguage(langName, infPathTextField.getText(),
                            irrPathTextField.getText(),
                            nounPathTextField.getText(),
                            corpPathTextField.getText());
                    langComboBox.addItem(langName);
                    okButton.setText("Save");
                    delButton.setEnabled(true);
                }
            }
        } catch (IOException IOEx) {
            String msg = IOEx.getMessage();
            JOptionPane.showMessageDialog(this, msg, "Error writing",
                      JOptionPane.ERROR_MESSAGE);
        }
        this.pack();
        this.repaint();
    }

    private void actionPerformedDoneButton(ActionEvent event) {
        LVC.ReturnToMain();
    }

    private void actionPerformedDelButton(ActionEvent event) {
        String langName = (String)langComboBox.getEditor().getItem();
        Object[] options = {"Yes", "No"};
        int n = JOptionPane.showOptionDialog(this, "Do you want to delete the "
                + "language " + langName + "?","Delete", 
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                null, options, options[1]);
        if (n == 0) {
            langComboBox.removeItem(langName);
            langComboBox.getEditor().setItem("");
            LVC.deleteLanguage(langName);
        }
    }

    private void assignListeners() {
        infButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedPathButtons(event, "infinitives");
            }
        });

        corpButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedPathButtons(event, "corpus");
            }
        });

        irrButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedPathButtons(event, "irregular verbs");
            }
        });

        nounButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedPathButtons(event, "nouns");
            }
        });

        okButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedOkButton(event);
            }
        });

        doneButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedDoneButton(event);
            }
        });

        delButton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedDelButton(event);
            }
        });

        JTextComponent tcComboBox = (JTextComponent) langComboBox.getEditor()
                .getEditorComponent();
        tcComboBox.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                actionPerformedLangComboBoxEdit();
            }

            public void removeUpdate(DocumentEvent e) {
                actionPerformedLangComboBoxEdit();
            }

            public void changedUpdate(DocumentEvent e) {
                actionPerformedLangComboBoxEdit();
            }

        });

        langComboBox.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent event) {
                actionPerformedLangComboBox();
            }
        });
        Document infDoc = infPathTextField.getDocument();
        infDoc.addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void removeUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void changedUpdate(DocumentEvent e) {
                checkEmpty();
            }

        });

        Document irrDoc = irrPathTextField.getDocument();
        irrDoc.addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void removeUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void changedUpdate(DocumentEvent e) {
                checkEmpty();
            }

        });

        Document nounDoc = nounPathTextField.getDocument();
        nounDoc.addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void removeUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void changedUpdate(DocumentEvent e) {
                checkEmpty();
            }

        });

        Document corpDoc = corpPathTextField.getDocument();
        corpDoc.addDocumentListener(new DocumentListener() {
            public void insertUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void removeUpdate(DocumentEvent e) {
                checkEmpty();
            }

            public void changedUpdate(DocumentEvent e) {
                checkEmpty();
            }
        });
    }

    private void iniFrame() {
        this.setMinimumSize(new Dimension(675, 270));
        this.setPreferredSize(this.getMinimumSize());
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        this.setTitle("Languages manager");
        JPanel contentPane = (JPanel) this.getContentPane();
        contentPane.add(mainPanel);
    }

    private void iniMainPanel() {
        infPathTextField.setPreferredSize(new Dimension(60, 25));
        corpPathTextField.setPreferredSize(new Dimension(60, 25));
        irrPathTextField.setPreferredSize(new Dimension(60, 25));
        nounPathTextField.setPreferredSize(new Dimension(60, 25));

        okButton.setPreferredSize(new Dimension(100, 25));
        doneButton.setPreferredSize(new Dimension(100, 25));
        delButton.setPreferredSize(new Dimension(100, 25));
        delButton.setEnabled(false);

        buttonsPanel.setLayout(new FlowLayout(FlowLayout.TRAILING));
        buttonsPanel.add(delButton);
        buttonsPanel.add(okButton);
        buttonsPanel.add(doneButton);

        GroupLayout layout = new GroupLayout(centralPanel);
        centralPanel.setLayout(layout);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup();
        hGroup.addGroup(layout.createParallelGroup()
            .addComponent(langLabel)
            .addGap(25)
            .addComponent(infLabel)
            .addComponent(irrLabel)
            .addComponent(nounLabel)
            .addComponent(corpLabel));
        hGroup.addGroup(layout.createParallelGroup()
            .addComponent(langComboBox)
            .addGap(25)
            .addComponent(infPathTextField)
            .addComponent(irrPathTextField)
            .addComponent(nounPathTextField)
            .addComponent(corpPathTextField)
            .addGap(25));
        hGroup.addGroup(layout.createParallelGroup()
            .addComponent(infButton)
            .addComponent(irrButton)
            .addComponent(nounButton)
            .addComponent(corpButton)
            .addGap(25));
        layout.setHorizontalGroup(hGroup);

        GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup();
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addComponent(langLabel)
            .addComponent(langComboBox));
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addGap(25)
            .addGap(25));
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addComponent(infLabel)
            .addComponent(infPathTextField)
            .addComponent(infButton));
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addComponent(irrLabel)
            .addComponent(irrPathTextField)
            .addComponent(irrButton));
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addComponent(nounLabel)
            .addComponent(nounPathTextField)
            .addComponent(nounButton));
        vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addComponent(corpLabel)
            .addComponent(corpPathTextField)
            .addComponent(corpButton));
         vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE)
            .addGap(25)
            .addGap(25));
        layout.setVerticalGroup(vGroup);

        mainPanel.setLayout(new BorderLayout());
        mainPanel.add(centralPanel, BorderLayout.CENTER);
        mainPanel.add(buttonsPanel, BorderLayout.SOUTH);
    }

    private void inilangComboBox() {
        String [] langs = LVC.getLanguagesNames();
        langComboBox.setEditable(true);
        langComboBox.removeAllItems();
        for (int i = 0; i < langs.length; ++i) {
            langComboBox.addItem(langs[i]);
        }
        actionPerformedLangComboBox();
        checkEmpty();
    }
}